// pages/tech/farm-suggest/detail/detail.js
//调用方式 /pages/tech/farm-suggest/detail/detail?appid=12&recordid=dcee
var httpUtil = require('../../../../utils/httpUtil.js')
var uiUtil = require('../../../../utils/uiUtil.js')
var emptyUtil = require('../../../templates/empty/empty.js')
const app = getApp()
var that

Page({

  /**
   * 页面的初始数据
   */
  data: {
    appId: null,
    recordId: null,
    data: null,

    identity: null,

    emptyParam: {
      emptyStatus: 0
    },

    curTopBarIndex: 0,

    //购物车
    selectedIdList: [], //已选择的购物车Id列表
    enableBuyCount: 0, //总的可购买数量
    saveAmount: '0.00', //节省金额
    totalAmount: '0.00', //总计金额

    dialogInputFocus: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    uiUtil.showLoading("正在加载..")
    var appId = options.appid
    var recordId = options.recordid
    if (!appId || !recordId) { //-退出
      wx.navigateBack({})
      return;
    }
    if (options.curTopBarIndex==1){
      that.setData({
        curTopBarIndex:1
      })
    }


    this.setData({
      appId: appId,
      recordId: recordId,
      identity: app.globalData.identity
    })

    this.requestData()
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return util.handleShareApp()
  },

  /**
   * 获取数据
   */
  requestData() {
    httpUtil.PostRequestHeaderApp("detail_app_plan", {
      appId: that.data.appId,
      recordId: that.data.recordId
    }, {
      success(res) {
        if (res) {
          //设置选择状态
          var enableBuyCount = 0
          for (var i = 0; i < res.groups.length; i++) {
            for (var a = 0; a < res.groups[i].products.length; a++){
              var item = res.groups[i].products[a]
              if (item.canBuy == '1') {
                enableBuyCount++;
              }
            }
          }

          that.setData({
            enableBuyCount: enableBuyCount,
            data: res
          })
        } else {
          emptyUtil.showFailView("获取信息失败")
        }
      },
      fail(code, res) {
        var text = emptyUtil.getErrText(code, res, "获取信息失败")
        emptyUtil.showFailView(text)
      },
      complete() {
        uiUtil.hideLoading()
      }
    })
  },

  /**
   * 选项卡切换
   */
  onSwithTabBar(e) {
    var index = e.target.dataset.current;
    if (index == this.data.curTopBarIndex) {
      return
    }

    this.setData({
      curTopBarIndex: index
    })
  },

  /**
   * 商品分组展开和关闭
   */
  titleClick(e){
    let indexs = e.currentTarget.dataset.indexs;
    let titleboolean = "data.groups[" + indexs +"].titleboolean";
    var titleblur=true;
    if (that.data.data.groups[indexs].titleboolean){
      titleblur=false;
    }
    that.setData({
      [titleboolean]: titleblur
    })
  },

  /**
   * 文件点击
   */
  onFileClick(e) {
    var index = e.currentTarget.dataset.index
    var fileItem = this.data.data.attachments[index]
    var url = encodeURIComponent(fileItem.filePath)
    var title = encodeURIComponent(fileItem.fileName)
    wx.navigateTo({
      url: '/pages/web/web?url=' + url + '&title=' + title
    })
  },

  //购物车
  /**
   * 购买数量-减少
   */
  onBugCountCutClick(e) {
    var index = e.currentTarget.dataset.index
    var indexs = e.currentTarget.dataset.indexs
    var goodItem = this.data.data.groups[indexs].products[index]
    var lastCount = goodItem.buyCount || 1;
    if (lastCount == 1) { //原数量为0
      return;
    } else {
      goodItem.buyCount = lastCount - 1
      this.setData({
        ['data.groups[' + indexs + '].products']: that.data.data.groups[indexs].products
      })
    }
    //重新计算金额
    that.calcuAmount()
  },

  /**
   * 购买数量-增加
   */
  onBugCountAddClick(e) {
    var index = e.currentTarget.dataset.index
    var indexs = e.currentTarget.dataset.indexs
    var goodItem = this.data.data.groups[indexs].products[index]
    var lastCount = goodItem.buyCount || 0
    goodItem.buyCount = lastCount + 1
    this.setData({
      ['data.groups[' + indexs + '].products']: that.data.data.groups[indexs].products
    })
    //重新计算金额
    that.calcuAmount()
  },

  // 手动输入数量
  onConfirmDialogInputClick() {
    this.setData({
      dialogInputFocus: true,
    })
  },
  cartInput(e) {
    var index = e.currentTarget.dataset.index
    var indexs = e.currentTarget.dataset.indexs
    var goodItem = this.data.data.groups[indexs].products[index]
    var count = parseInt(e.detail.value) || 1
    goodItem.buyCount = count
    this.setData({
      ['data.groups[' + indexs + '].products']: that.data.data.groups[indexs].products
    })
  },

  /**
   * item点击
   */
  onCardItemClick(e) {
    var index = e.currentTarget.dataset.index
    var indexs = e.currentTarget.dataset.indexs

    var clickItem = this.data.data.groups[indexs].products[index]
    wx.navigateTo({
      url: '/pages/goods/goods-detail/goods-detail?goodId=' + clickItem.goodId + '&skuId=' + clickItem.skuId
    })
  },

  /**
   * 分组点击
   */
  onCartItemsSelectClick(e){
    var indexs = e.currentTarget.dataset.indexs
    var cartList = this.data.data.groups[indexs].products
    var notIsSelected = this.data.data.groups[indexs].notIsSelected
    for (var i = 0; i < cartList.length; i++) {
      var clickItem = cartList[i]
      if (clickItem.canBuy != '1') {

      } else {
        var goodId = clickItem.goodId;
        var selectedIdList = this.data.selectedIdList;
        var selectedIdIndex = selectedIdList.indexOf(goodId)

        if (selectedIdIndex >= 0 && notIsSelected==0) { //已选择该商品
          selectedIdList.splice(selectedIdIndex, 1);
          clickItem.tIsSelected = false;
          app.cartSelectsDel(clickItem.goodId, clickItem.skuId)
        } else {
          selectedIdList.unshift(goodId);
          clickItem.tIsSelected = true;
          app.cartSelectsAdd(clickItem.goodId, clickItem.skuId)
        }
      }
      
    }
    

    this.setData({
      ['data.groups[' + indexs + '].products']: cartList,
      selectedIdList: selectedIdList,
    })
    this.calcuAmount()

  },

  /**
   * 购物车选择item点击
   */
  onCartItemSelectClick(e) {
    var index = e.currentTarget.dataset.index
    var indexs = e.currentTarget.dataset.indexs
    var cartList = this.data.data.groups[indexs].products
    var clickItem = cartList[index]

    if (clickItem.canBuy != '1') {
      return;
    }

    var goodId = clickItem.goodId;

    var selectedIdList = this.data.selectedIdList;

    var selectedIdIndex = selectedIdList.indexOf(goodId)
    if (selectedIdIndex >= 0) { //已选择该商品
      selectedIdList.splice(selectedIdIndex, 1);
      clickItem.tIsSelected = false;
      app.cartSelectsDel(clickItem.goodId, clickItem.skuId)
    } else {
      selectedIdList.unshift(goodId);
      clickItem.tIsSelected = true;
      app.cartSelectsAdd(clickItem.goodId, clickItem.skuId)
    }

    this.setData({
      ['data.groups['+indexs+'].products']: cartList,
      selectedIdList: selectedIdList,
    })
    this.calcuAmount()

  },
  /**
   * 全选点击
   */
  onselectAllClick() {
    var selectedIdList = [];
    var storageSelectedList = []; //需存储的已选择商品信息

    for (var a = 0; a < this.data.data.groups.length; a++) {
      var cartList = this.data.data.groups[a].products
      var length = cartList.length

      for (var i = 0; i < length; i++) {
        var item = cartList[i]
        if (item.canBuy != '1') {
          continue;
        }
        item.tIsSelected = true
        selectedIdList.unshift(item.goodId)
      }
      this.setData({
        ['data.groups[' + a + '].products']: cartList
      })
    };

    this.setData({
      selectedIdList: selectedIdList,
    })

    this.calcuAmount()
  },

  /**
   * 全不选点击
   */
  ondisSelectAllClick() {
    for (var a = 0; a < this.data.data.groups.length; a++) {
      var cartList = this.data.data.groups[a].products
      var length = cartList.length
      for (var i = 0; i < length; i++) {
        var item = cartList[i]
        item.tIsSelected = false
      }
      this.setData({
        ['data.groups[' + a + '].products']: cartList
      })
    }
    this.setData({
      selectedIdList: [],
    })

    this.calcuAmount()
  },

  /**
   * 计算金额
   */
  calcuAmount() {
    that.selectAll();
    var groups = this.data.data.groups;
    var saveAmount = 0;
    var totalAmount = 0;
    for (var a = 0; a < this.data.data.groups.length; a++){
      var cartList = groups[a].products
      var identity = this.data.identity;
      var length = cartList.length

      for (var i = 0; i < length; i++) {
        var item = cartList[i]
        if (item.tIsSelected) {
          //（市场价-vip价格）x数量
          var everySaveAmount = item.basePrice - item.vipPrice
          if (everySaveAmount > 0) {
            saveAmount = saveAmount + (everySaveAmount * item.buyCount)
          }
          //区分合计会员价和合计市场价
          if (identity == 1) {
            totalAmount += (item.vipPrice * item.buyCount)
          } else {
            totalAmount += (item.basePrice * item.buyCount)
          }
        }
      }
    }
    
    saveAmount = saveAmount.toFixed(2);
    totalAmount = totalAmount.toFixed(2);

    this.setData({
      saveAmount: saveAmount,
      totalAmount: totalAmount
    })
  },

  /**
   * 提交订单
   */
  selectAll(){
    for (var a = 0; a < this.data.data.groups.length; a++) {
      var notIsSelected=0;
      var products = this.data.data.groups[a].products;
      for (var i = 0; i < products.length; i++) {
        var item =products[i];
        if (item.canBuy == 1 && !item.tIsSelected){
          notIsSelected++;
        }
      }
      that.setData({
        ['data.groups[' + a + '].notIsSelected']: notIsSelected
      })
    }
  },

  /**
   * 提交订单
   */
  // onSubmitOrder() {
  //   var selectedIdList = this.data.selectedIdList
  //   var selectedIdLength = selectedIdList.length
  //   if (selectedIdLength == 0) {
  //     uiUtil.showToast("请选择商品..")
  //     return
  //   }
  //   var resultList = []
  //   var cartList = this.data.data.products
  //   var cartListLength = cartList.length
  //   for (var i = 0; i < cartListLength; i++) {
  //     var cartItem = cartList[i]
  //     if (cartItem.tIsSelected && cartItem.buyCount > 0) {
  //       resultList.push(cartItem)
  //     }
  //   }

  //   wx.navigateTo({
  //     url: '/pages/order/pre-order/pre-order?goodList=' + encodeURIComponent(JSON.stringify(resultList)) + '&appid=' + that.data.appId + '&planid=' + that.data.data.planId,
  //   })

  // },
  onSubmitOrder() {
    var selectedIdList = this.data.selectedIdList
    var selectedIdLength = selectedIdList.length
    if (selectedIdLength == 0) {
      uiUtil.showToast("请选择商品..")
      return
    }

    uiUtil.showLoading("加载中..")
    var groups = []
    for (var a = 0; a < that.data.data.groups.length; a++) {
      var products=[]
      var cartList = this.data.data.groups[a].products
      var cartListLength = cartList.length
      for (var i = 0; i < cartListLength; i++) {
        var cartItem = cartList[i]
        if (cartItem.tIsSelected && cartItem.buyCount > 0) {
          products.push({
            skuProductId: cartItem.goodId,
            num: cartItem.buyCount
          })
        }
      }
      if (products.length>0){
        groups.push({
          code: that.data.data.groups[a].groupCode,
          products: products
        })
      }
    }
    
    httpUtil.PostRequestHeaderApp("pre_plan_submit_order", {
      appId: that.data.appId,
      planId: that.data.data.planId,
      groups: groups
    }, {
      success(res) {
        
        wx.navigateTo({
          url: '/pages/order/pre-order/pre-order?goodList=' + encodeURIComponent(JSON.stringify(res.goodList)) + '&appid=' + that.data.appId + '&planid=' + res.planId,
        })
      },
      fail(code, res) {
        emptyUtil.showFailView(res)
      },
      complete() {
        uiUtil.hideLoading()
      }
    })

  },

  /**
   * 去评价
   */
  onFeedBackClick(e) {
    var appId = that.data.appId
    var recordId = that.data.recordId
    var satisfaction = that.data.data.satisfaction
    wx.navigateTo({
      url: '/pages/tech/farm-suggest/feedback/feedback?appid=' + appId + '&recordid=' + recordId + '&satisfaction=' + encodeURIComponent(JSON.stringify(satisfaction)),
    })
  },

  /**
   * 
   */
  onContactClick(e) {
    var phoneNo = this.data.data.telphone;
    if (phoneNo) {
      wx.makePhoneCall({
        phoneNumber: phoneNo,
      })
    }
  }
})